package com.example.myDesignPatterns.行为型模式.责任链模式Responsibility.用责任链模式处理全局异常.handler;

import org.springframework.http.ResponseEntity;

import java.util.List;
import java.util.Optional;

public class ExceptionHandlerChainBuilder {
    private final List<ExceptionHandler> handlers;

    public ExceptionHandlerChainBuilder(List<ExceptionHandler> handlers) {
        this.handlers = handlers;
    }

    public ExceptionHandler build() {
        return new ChainExceptionHandler();

    }
    private class ChainExceptionHandler implements ExceptionHandler {
        @Override
        public boolean supports(Exception exception) {
            // 这里不需要实现，因为我们将在 handle 方法中查找合适的处理器
            throw new UnsupportedOperationException("This method is not supported.");
        }

        @Override
        public ResponseEntity<Object> handle(Exception exception) {
            // 寻找能够处理此异常的第一个处理器
            ResponseEntity<Object> noHandlerFoundForException = handlers.stream()
                    .filter(handler -> handler.supports(exception))
                    .findFirst()
                    .orElseGet(this::getDefaultExceptionHandler)
                    .handle(exception);
          return noHandlerFoundForException;
        }

        private ExceptionHandler getDefaultExceptionHandler() {
            // 假设 DefaultExceptionHandler 总是存在于 handlers 列表中
            return handlers.stream()
                    .filter(h -> h instanceof DefaultExceptionHandler)
                    .findFirst()
                    .orElseThrow(() -> new IllegalStateException("DefaultExceptionHandler not found in the handlers list"));
        }
    }
}

